home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gdata / gdata / service.py < prev    next >
Encoding:
Python Source  |  2009-02-11  |  64.4 KB  |  1,627 lines

  1. #
  2. # Copyright (C) 2006,2008 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #      http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16.  
  17. """GDataService provides CRUD ops. and programmatic login for GData services.
  18.  
  19.   Error: A base exception class for all exceptions in the gdata_client
  20.          module.
  21.  
  22.   CaptchaRequired: This exception is thrown when a login attempt results in a
  23.                    captcha challenge from the ClientLogin service. When this
  24.                    exception is thrown, the captcha_token and captcha_url are
  25.                    set to the values provided in the server's response.
  26.  
  27.   BadAuthentication: Raised when a login attempt is made with an incorrect
  28.                      username or password.
  29.  
  30.   NotAuthenticated: Raised if an operation requiring authentication is called
  31.                     before a user has authenticated.
  32.  
  33.   NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
  34.                    the user is either not authenticated or is authenticated
  35.                    through another authentication mechanism.
  36.  
  37.   NonOAuthToken: Raised if a method to modify an OAuth token is used when the
  38.                  user is either not authenticated or is authenticated through
  39.                  another authentication mechanism.
  40.  
  41.   RequestError: Raised if a CRUD request returned a non-success code. 
  42.  
  43.   UnexpectedReturnType: Raised if the response from the server was not of the
  44.                         desired type. For example, this would be raised if the
  45.                         server sent a feed when the client requested an entry.
  46.  
  47.   GDataService: Encapsulates user credentials needed to perform insert, update
  48.                 and delete operations with the GData API. An instance can
  49.                 perform user authentication, query, insertion, deletion, and 
  50.                 update.
  51.  
  52.   Query: Eases query URI creation by allowing URI parameters to be set as 
  53.          dictionary attributes. For example a query with a feed of 
  54.          '/base/feeds/snippets' and ['bq'] set to 'digital camera' will 
  55.          produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is 
  56.          called on it.
  57. """
  58.  
  59.  
  60. __author__ = 'api.jscudder (Jeffrey Scudder)'
  61.  
  62.  
  63. import re
  64. import urllib
  65. import urlparse
  66. try:
  67.   from xml.etree import cElementTree as ElementTree
  68. except ImportError:
  69.   try:
  70.     import cElementTree as ElementTree
  71.   except ImportError:
  72.     try:
  73.       from xml.etree import ElementTree
  74.     except ImportError:
  75.       from elementtree import ElementTree
  76. import atom.service
  77. import gdata
  78. import atom
  79. import atom.http_interface
  80. import atom.token_store
  81. import gdata.auth
  82.  
  83.  
  84. AUTH_SERVER_HOST = 'https://www.google.com'
  85.  
  86.  
  87. # When requesting an AuthSub token, it is often helpful to track the scope
  88. # which is being requested. One way to accomplish this is to add a URL 
  89. # parameter to the 'next' URL which contains the requested scope. This
  90. # constant is the default name (AKA key) for the URL parameter.
  91. SCOPE_URL_PARAM_NAME = 'authsub_token_scope'
  92. # When requesting an OAuth access token or authorization of an existing OAuth
  93. # request token, it is often helpful to track the scope(s) which is/are being
  94. # requested. One way to accomplish this is to add a URL parameter to the
  95. # 'callback' URL which contains the requested scope. This constant is the
  96. # default name (AKA key) for the URL parameter.
  97. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope'
  98. # Maps the service names used in ClientLogin to scope URLs.
  99. CLIENT_LOGIN_SCOPES = {
  100.     'cl': [ # Google Calendar
  101.         'https://www.google.com/calendar/feeds/',
  102.         'http://www.google.com/calendar/feeds/'],
  103.     'gbase': [ # Google Base
  104.         'http://base.google.com/base/feeds/',
  105.         'http://www.google.com/base/feeds/'], 
  106.     'blogger': [ # Blogger
  107.         'http://www.blogger.com/feeds/'], 
  108.     'codesearch': [ # Google Code Search
  109.         'http://www.google.com/codesearch/feeds/'],
  110.     'cp': [ # Contacts API
  111.         'https://www.google.com/m8/feeds/',
  112.         'http://www.google.com/m8/feeds/'],
  113.     'finance': [ # Google Finance
  114.         'http://finance.google.com/finance/feeds/'],
  115.     'health': [ # Google Health
  116.         'https://www.google.com/health/feeds/'],
  117.     'writely': [ # Documents List API
  118.         'https://docs.google.com/feeds/',
  119.         'http://docs.google.com/feeds/'],
  120.     'lh2': [ # Picasa Web Albums
  121.         'http://picasaweb.google.com/data/'],
  122.     'apps': [ # Google Apps Provisioning API
  123.         'http://www.google.com/a/feeds/',
  124.         'https://www.google.com/a/feeds/',
  125.         'http://apps-apis.google.com/a/feeds/',
  126.         'https://apps-apis.google.com/a/feeds/'],
  127.     'weaver': [ # Health H9 Sandbox
  128.         'https://www.google.com/h9/'],
  129.     'wise': [ # Spreadsheets Data API
  130.         'https://spreadsheets.google.com/feeds/',
  131.         'http://spreadsheets.google.com/feeds/'],
  132.     'sitemaps': [ # Google Webmaster Tools
  133.         'https://www.google.com/webmasters/tools/feeds/'],
  134.     'youtube': [ # YouTube
  135.         'http://gdata.youtube.com/feeds/api/',
  136.         'http://uploads.gdata.youtube.com/feeds/api',
  137.         'http://gdata.youtube.com/action/GetUploadToken']}
  138.  
  139.  
  140. def lookup_scopes(service_name):
  141.   """Finds the scope URLs for the desired service.
  142.   
  143.   In some cases, an unknown service may be used, and in those cases this
  144.   function will return None.
  145.   """
  146.   if service_name in CLIENT_LOGIN_SCOPES:
  147.     return CLIENT_LOGIN_SCOPES[service_name]
  148.   return None
  149.     
  150.  
  151. # Module level variable specifies which module should be used by GDataService
  152. # objects to make HttpRequests. This setting can be overridden on each 
  153. # instance of GDataService.
  154. # This module level variable is deprecated. Reassign the http_client member
  155. # of a GDataService object instead.
  156. http_request_handler = atom.service
  157.  
  158.  
  159. class Error(Exception):
  160.   pass
  161.  
  162.  
  163. class CaptchaRequired(Error):
  164.   pass
  165.  
  166.  
  167. class BadAuthentication(Error):
  168.   pass
  169.  
  170.  
  171. class NotAuthenticated(Error):
  172.   pass
  173.  
  174.  
  175. class NonAuthSubToken(Error):
  176.   pass
  177.  
  178.  
  179. class NonOAuthToken(Error):
  180.   pass
  181.  
  182.  
  183. class RequestError(Error):
  184.   pass
  185.  
  186.  
  187. class UnexpectedReturnType(Error):
  188.   pass
  189.  
  190.  
  191. class BadAuthenticationServiceURL(Error):
  192.   pass
  193.  
  194.  
  195. class FetchingOAuthRequestTokenFailed(RequestError):
  196.   pass
  197.  
  198.  
  199. class TokenUpgradeFailed(RequestError):
  200.   pass
  201.  
  202.  
  203. class RevokingOAuthTokenFailed(RequestError):
  204.   pass
  205.  
  206.  
  207. class AuthorizationRequired(Error):
  208.   pass
  209.  
  210.  
  211. class TokenHadNoScope(Error):
  212.   pass
  213.  
  214.  
  215. class GDataService(atom.service.AtomService):
  216.   """Contains elements needed for GData login and CRUD request headers.
  217.  
  218.   Maintains additional headers (tokens for example) needed for the GData 
  219.   services to allow a user to perform inserts, updates, and deletes.
  220.   """
  221.   # The hander member is deprecated, use http_client instead.
  222.   handler = None
  223.   # The auth_token member is deprecated, use the token_store instead.
  224.   auth_token = None
  225.   # The tokens dict is deprecated in favor of the token_store.
  226.   tokens = None
  227.  
  228.   def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
  229.                service=None, auth_service_url=None, source=None, server=None, 
  230.                additional_headers=None, handler=None, tokens=None,
  231.                http_client=None, token_store=None):
  232.     """Creates an object of type GDataService.
  233.  
  234.     Args:
  235.       email: string (optional) The user's email address, used for
  236.           authentication.
  237.       password: string (optional) The user's password.
  238.       account_type: string (optional) The type of account to use. Use
  239.           'GOOGLE' for regular Google accounts or 'HOSTED' for Google
  240.           Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
  241.           account first and, if it doesn't exist, try finding a regular
  242.           GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
  243.       service: string (optional) The desired service for which credentials
  244.           will be obtained.
  245.       auth_service_url: string (optional) User-defined auth token request URL
  246.           allows users to explicitly specify where to send auth token requests.
  247.       source: string (optional) The name of the user's application.
  248.       server: string (optional) The name of the server to which a connection
  249.           will be opened. Default value: 'base.google.com'.
  250.       additional_headers: dictionary (optional) Any additional headers which 
  251.           should be included with CRUD operations.
  252.       handler: module (optional) This parameter is deprecated and has been
  253.           replaced by http_client.
  254.       tokens: This parameter is deprecated, calls should be made to 
  255.           token_store instead.
  256.       http_client: An object responsible for making HTTP requests using a
  257.           request method. If none is provided, a new instance of
  258.           atom.http.ProxiedHttpClient will be used.
  259.       token_store: Keeps a collection of authorization tokens which can be
  260.           applied to requests for a specific URLs. Critical methods are
  261.           find_token based on a URL (atom.url.Url or a string), add_token,
  262.           and remove_token.
  263.     """
  264.     atom.service.AtomService.__init__(self, http_client=http_client, 
  265.         token_store=token_store)
  266.     self.email = email
  267.     self.password = password
  268.     self.account_type = account_type
  269.     self.service = service
  270.     self.auth_service_url = auth_service_url
  271.     self.server = server
  272.     self.additional_headers = additional_headers or {}
  273.     self._oauth_input_params = None
  274.     self.__SetSource(source)
  275.     self.__captcha_token = None
  276.     self.__captcha_url = None
  277.     self.__gsessionid = None
  278.  
  279.     if http_request_handler.__name__ == 'gdata.urlfetch':
  280.       import gdata.alt.appengine
  281.       self.http_client = gdata.alt.appengine.AppEngineHttpClient()
  282.  
  283.   # Define properties for GDataService
  284.   def _SetAuthSubToken(self, auth_token, scopes=None):
  285.     """Deprecated, use SetAuthSubToken instead."""
  286.     self.SetAuthSubToken(auth_token, scopes=scopes)
  287.  
  288.   def __SetAuthSubToken(self, auth_token, scopes=None):
  289.     """Deprecated, use SetAuthSubToken instead."""
  290.     self._SetAuthSubToken(auth_token, scopes=scopes)
  291.  
  292.   def _GetAuthToken(self):
  293.     """Returns the auth token used for authenticating requests.
  294.  
  295.     Returns:
  296.       string
  297.     """
  298.     current_scopes = lookup_scopes(self.service)
  299.     if current_scopes:
  300.       token = self.token_store.find_token(current_scopes[0])
  301.       if hasattr(token, 'auth_header'):
  302.         return token.auth_header
  303.     return None
  304.  
  305.   def _GetCaptchaToken(self):
  306.     """Returns a captcha token if the most recent login attempt generated one.
  307.  
  308.     The captcha token is only set if the Programmatic Login attempt failed 
  309.     because the Google service issued a captcha challenge.
  310.  
  311.     Returns:
  312.       string
  313.     """
  314.     return self.__captcha_token
  315.  
  316.   def __GetCaptchaToken(self):
  317.     return self._GetCaptchaToken()
  318.  
  319.   captcha_token = property(__GetCaptchaToken,
  320.       doc="""Get the captcha token for a login request.""")
  321.  
  322.   def _GetCaptchaURL(self):
  323.     """Returns the URL of the captcha image if a login attempt generated one.
  324.      
  325.     The captcha URL is only set if the Programmatic Login attempt failed
  326.     because the Google service issued a captcha challenge.
  327.  
  328.     Returns:
  329.       string
  330.     """
  331.     return self.__captcha_url
  332.  
  333.   def __GetCaptchaURL(self):
  334.     return self._GetCaptchaURL()
  335.  
  336.   captcha_url = property(__GetCaptchaURL,
  337.       doc="""Get the captcha URL for a login request.""")
  338.  
  339.   def SetOAuthInputParameters(self, signature_method, consumer_key,
  340.                               consumer_secret=None, rsa_key=None,
  341.                               two_legged_oauth=False):
  342.     """Sets parameters required for using OAuth authentication mechanism.
  343.     
  344.     NOTE: Though consumer_secret and rsa_key are optional, either of the two
  345.     is required depending on the value of the signature_method.
  346.     
  347.     Args:
  348.       signature_method: class which provides implementation for strategy class
  349.           oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  350.           signing each request. Valid implementations are provided as the
  351.           constants defined by gdata.auth.OAuthSignatureMethod. Currently
  352.           they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  353.           gdata.auth.OAuthSignatureMethod.HMAC_SHA1
  354.       consumer_key: string Domain identifying third_party web application.
  355.       consumer_secret: string (optional) Secret generated during registration.
  356.           Required only for HMAC_SHA1 signature method.
  357.       rsa_key: string (optional) Private key required for RSA_SHA1 signature
  358.           method.
  359.       two_legged_oauth: string (default=False) Enables two-legged OAuth process.
  360.     """
  361.     self._oauth_input_params = gdata.auth.OAuthInputParams(
  362.         signature_method, consumer_key, consumer_secret=consumer_secret,
  363.         rsa_key=rsa_key)
  364.     if two_legged_oauth:
  365.       oauth_token = gdata.auth.OAuthToken(
  366.           oauth_input_params=self._oauth_input_params)
  367.       self.SetOAuthToken(oauth_token)
  368.   
  369.   def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None,
  370.                              request_url='%s/accounts/OAuthGetRequestToken' % \
  371.                              AUTH_SERVER_HOST):
  372.     """Fetches OAuth request token and returns it.
  373.     
  374.     Args:
  375.       scopes: string or list of string base URL(s) of the service(s) to be
  376.           accessed. If None, then this method tries to determine the
  377.           scope(s) from the current service.
  378.       extra_parameters: dict (optional) key-value pairs as any additional
  379.           parameters to be included in the URL and signature while making a
  380.           request for fetching an OAuth request token. All the OAuth parameters
  381.           are added by default. But if provided through this argument, any
  382.           default parameters will be overwritten. For e.g. a default parameter
  383.           oauth_version 1.0 can be overwritten if
  384.           extra_parameters = {'oauth_version': '2.0'}
  385.       request_url: Request token URL. The default is
  386.           'https://www.google.com/accounts/OAuthGetRequestToken'.
  387.       
  388.     Returns:
  389.       The fetched request token as a gdata.auth.OAuthToken object.
  390.       
  391.     Raises:
  392.       FetchingOAuthRequestTokenFailed if the server responded to the request
  393.       with an error.
  394.     """
  395.     if scopes is None:
  396.       scopes = lookup_scopes(self.service)
  397.     if not isinstance(scopes, (list, tuple)):
  398.       scopes = [scopes,]
  399.     request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl(
  400.         self._oauth_input_params, scopes,
  401.         request_token_url=request_url,
  402.         extra_parameters=extra_parameters)
  403.     response = self.http_client.request('GET', str(request_token_url))
  404.     if response.status == 200:
  405.       token = gdata.auth.OAuthToken()
  406.       token.set_token_string(response.read())
  407.       token.scopes = scopes
  408.       token.oauth_input_params = self._oauth_input_params
  409.       return token
  410.     error = {
  411.         'status': response.status,
  412.         'reason': 'Non 200 response on upgrade',
  413.         'body': response.read()
  414.         }
  415.     raise FetchingOAuthRequestTokenFailed(error)    
  416.   
  417.   def SetOAuthToken(self, oauth_token):
  418.     """Attempts to set the current token and add it to the token store.
  419.     
  420.     The oauth_token can be any OAuth token i.e. unauthorized request token,
  421.     authorized request token or access token.
  422.     This method also attempts to add the token to the token store.
  423.     Use this method any time you want the current token to point to the
  424.     oauth_token passed. For e.g. call this method with the request token
  425.     you receive from FetchOAuthRequestToken.
  426.     
  427.     Args:
  428.       request_token: gdata.auth.OAuthToken OAuth request token.
  429.     """
  430.     if self.auto_set_current_token:
  431.       self.current_token = oauth_token
  432.     if self.auto_store_tokens:
  433.       self.token_store.add_token(oauth_token)
  434.     
  435.   def GenerateOAuthAuthorizationURL(
  436.       self, request_token=None, callback_url=None, extra_params=None,
  437.       include_scopes_in_callback=False,
  438.       scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME,
  439.       request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST):
  440.     """Generates URL at which user will login to authorize the request token.
  441.     
  442.     Args:
  443.       request_token: gdata.auth.OAuthToken (optional) OAuth request token.
  444.           If not specified, then the current token will be used if it is of
  445.           type <gdata.auth.OAuthToken>, else it is found by looking in the
  446.           token_store by looking for a token for the current scope.    
  447.       callback_url: string (optional) The URL user will be sent to after
  448.           logging in and granting access.
  449.       extra_params: dict (optional) Additional parameters to be sent.
  450.       include_scopes_in_callback: Boolean (default=False) if set to True, and
  451.           if 'callback_url' is present, the 'callback_url' will be modified to
  452.           include the scope(s) from the request token as a URL parameter. The
  453.           key for the 'callback' URL's scope parameter will be
  454.           OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  455.           a parameter to the 'callback' URL, is that the page which receives
  456.           the OAuth token will be able to tell which URLs the token grants
  457.           access to.
  458.       scopes_param_prefix: string (default='oauth_token_scope') The URL
  459.           parameter key which maps to the list of valid scopes for the token.
  460.           This URL parameter will be included in the callback URL along with
  461.           the scopes of the token as value if include_scopes_in_callback=True.
  462.       request_url: Authorization URL. The default is
  463.           'https://www.google.com/accounts/OAuthAuthorizeToken'.
  464.     Returns:
  465.       A string URL at which the user is required to login.
  466.     
  467.     Raises:
  468.       NonOAuthToken if the user's request token is not an OAuth token or if a
  469.       request token was not available.
  470.     """
  471.     if request_token and not isinstance(request_token, gdata.auth.OAuthToken):
  472.       raise NonOAuthToken
  473.     if not request_token:
  474.       if isinstance(self.current_token, gdata.auth.OAuthToken):
  475.         request_token = self.current_token
  476.       else:
  477.         current_scopes = lookup_scopes(self.service)
  478.         if current_scopes:
  479.           token = self.token_store.find_token(current_scopes[0])
  480.           if isinstance(token, gdata.auth.OAuthToken):
  481.             request_token = token
  482.     if not request_token:
  483.       raise NonOAuthToken
  484.     return str(gdata.auth.GenerateOAuthAuthorizationUrl(
  485.         request_token,
  486.         authorization_url=request_url,
  487.         callback_url=callback_url, extra_params=extra_params,
  488.         include_scopes_in_callback=include_scopes_in_callback,
  489.         scopes_param_prefix=scopes_param_prefix))   
  490.   
  491.   def UpgradeToOAuthAccessToken(self, authorized_request_token=None,
  492.                                 request_url='%s/accounts/OAuthGetAccessToken' \
  493.                                 % AUTH_SERVER_HOST, oauth_version='1.0'):
  494.     """Upgrades the authorized request token to an access token.
  495.     
  496.     Args:
  497.       authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request
  498.           token. If not specified, then the current token will be used if it is
  499.           of type <gdata.auth.OAuthToken>, else it is found by looking in the
  500.           token_store by looking for a token for the current scope.
  501.       oauth_version: str (default='1.0') oauth_version parameter. All other
  502.           'oauth_' parameters are added by default. This parameter too, is
  503.           added by default but here you can override it's value.
  504.       request_url: Access token URL. The default is
  505.           'https://www.google.com/accounts/OAuthGetAccessToken'.
  506.           
  507.     Raises:
  508.       NonOAuthToken if the user's authorized request token is not an OAuth
  509.       token or if an authorized request token was not available.
  510.       TokenUpgradeFailed if the server responded to the request with an 
  511.       error.
  512.     """
  513.     if (authorized_request_token and
  514.         not isinstance(authorized_request_token, gdata.auth.OAuthToken)):
  515.       raise NonOAuthToken
  516.     if not authorized_request_token:
  517.       if isinstance(self.current_token, gdata.auth.OAuthToken):
  518.         authorized_request_token = self.current_token
  519.       else:
  520.         current_scopes = lookup_scopes(self.service)
  521.         if current_scopes:
  522.           token = self.token_store.find_token(current_scopes[0])
  523.           if isinstance(token, gdata.auth.OAuthToken):
  524.             authorized_request_token = token
  525.     if not authorized_request_token:
  526.       raise NonOAuthToken
  527.     access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl(
  528.         authorized_request_token,
  529.         self._oauth_input_params,
  530.         access_token_url=request_url,
  531.         oauth_version=oauth_version)
  532.     response = self.http_client.request('GET', str(access_token_url))
  533.     if response.status == 200:
  534.       token = gdata.auth.OAuthTokenFromHttpBody(response.read())
  535.       token.scopes = authorized_request_token.scopes
  536.       token.oauth_input_params = authorized_request_token.oauth_input_params
  537.       self.SetOAuthToken(token)
  538.     else:
  539.       raise TokenUpgradeFailed({'status': response.status,
  540.                                 'reason': 'Non 200 response on upgrade',
  541.                                 'body': response.read()})      
  542.   
  543.   def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \
  544.                        AUTH_SERVER_HOST):
  545.     """Revokes an existing OAuth token.
  546.  
  547.     request_url: Token revoke URL. The default is
  548.           'https://www.google.com/accounts/AuthSubRevokeToken'.
  549.     Raises:
  550.       NonOAuthToken if the user's auth token is not an OAuth token.
  551.       RevokingOAuthTokenFailed if request for revoking an OAuth token failed.
  552.     """
  553.     scopes = lookup_scopes(self.service)
  554.     token = self.token_store.find_token(scopes[0])
  555.     if not isinstance(token, gdata.auth.OAuthToken):
  556.       raise NonOAuthToken
  557.  
  558.     response = token.perform_request(self.http_client, 'GET', request_url,
  559.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  560.     if response.status == 200:
  561.       self.token_store.remove_token(token)
  562.     else:
  563.       raise RevokingOAuthTokenFailed
  564.   
  565.   def GetAuthSubToken(self):
  566.     """Returns the AuthSub token as a string.
  567.      
  568.     If the token is an gdta.auth.AuthSubToken, the Authorization Label
  569.     ("AuthSub token") is removed.
  570.  
  571.     This method examines the current_token to see if it is an AuthSubToken
  572.     or SecureAuthSubToken. If not, it searches the token_store for a token
  573.     which matches the current scope.
  574.     
  575.     The current scope is determined by the service name string member.
  576.     
  577.     Returns:
  578.       If the current_token is set to an AuthSubToken/SecureAuthSubToken,
  579.       return the token string. If there is no current_token, a token string
  580.       for a token which matches the service object's default scope is returned.
  581.       If there are no tokens valid for the scope, returns None.
  582.     """
  583.     if isinstance(self.current_token, gdata.auth.AuthSubToken):
  584.       return self.current_token.get_token_string()
  585.     current_scopes = lookup_scopes(self.service)
  586.     if current_scopes:
  587.       token = self.token_store.find_token(current_scopes[0])
  588.       if isinstance(token, gdata.auth.AuthSubToken):
  589.         return token.get_token_string()
  590.     else:
  591.       token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  592.       if isinstance(token, gdata.auth.ClientLoginToken):
  593.         return token.get_token_string()
  594.       return None
  595.  
  596.   def SetAuthSubToken(self, token, scopes=None, rsa_key=None):
  597.     """Sets the token sent in requests to an AuthSub token.
  598.  
  599.     Sets the current_token and attempts to add the token to the token_store.
  600.     
  601.     Only use this method if you have received a token from the AuthSub
  602.     service. The auth token is set automatically when UpgradeToSessionToken()
  603.     is used. See documentation for Google AuthSub here:
  604.     http://code.google.com/apis/accounts/AuthForWebApps.html 
  605.  
  606.     Args:
  607.      token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string
  608.             The token returned by the AuthSub service. If the token is an
  609.             AuthSubToken or SecureAuthSubToken, the scope information stored in
  610.             the token is used. If the token is a string, the scopes parameter is
  611.             used to determine the valid scopes.
  612.      scopes: list of URLs for which the token is valid. This is only used
  613.              if the token parameter is a string.
  614.      rsa_key: string (optional) Private key required for RSA_SHA1 signature
  615.               method.  This parameter is necessary if the token is a string
  616.               representing a secure token.
  617.     """
  618.     if not isinstance(token, gdata.auth.AuthSubToken):
  619.       token_string = token
  620.       if rsa_key:
  621.         token = gdata.auth.SecureAuthSubToken(rsa_key)
  622.       else:
  623.         token = gdata.auth.AuthSubToken()
  624.  
  625.       token.set_token_string(token_string)
  626.         
  627.     # If no scopes were set for the token, use the scopes passed in, or
  628.     # try to determine the scopes based on the current service name. If
  629.     # all else fails, set the token to match all requests.
  630.     if not token.scopes:
  631.       if scopes is None:
  632.         scopes = lookup_scopes(self.service)
  633.         if scopes is None:
  634.           scopes = [atom.token_store.SCOPE_ALL]
  635.       token.scopes = scopes
  636.     if self.auto_set_current_token:
  637.       self.current_token = token
  638.     if self.auto_store_tokens:
  639.       self.token_store.add_token(token)
  640.  
  641.   def GetClientLoginToken(self):
  642.     """Returns the token string for the current token or a token matching the 
  643.     service scope.
  644.  
  645.     If the current_token is a ClientLoginToken, the token string for 
  646.     the current token is returned. If the current_token is not set, this method
  647.     searches for a token in the token_store which is valid for the service 
  648.     object's current scope.
  649.  
  650.     The current scope is determined by the service name string member.
  651.     The token string is the end of the Authorization header, it doesn not
  652.     include the ClientLogin label.
  653.     """
  654.     if isinstance(self.current_token, gdata.auth.ClientLoginToken):
  655.       return self.current_token.get_token_string()
  656.     current_scopes = lookup_scopes(self.service)
  657.     if current_scopes:
  658.       token = self.token_store.find_token(current_scopes[0])
  659.       if isinstance(token, gdata.auth.ClientLoginToken):
  660.         return token.get_token_string()
  661.     else:
  662.       token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  663.       if isinstance(token, gdata.auth.ClientLoginToken):
  664.         return token.get_token_string()
  665.       return None
  666.  
  667.   def SetClientLoginToken(self, token, scopes=None):
  668.     """Sets the token sent in requests to a ClientLogin token.
  669.  
  670.     This method sets the current_token to a new ClientLoginToken and it 
  671.     also attempts to add the ClientLoginToken to the token_store.
  672.     
  673.     Only use this method if you have received a token from the ClientLogin
  674.     service. The auth_token is set automatically when ProgrammaticLogin()
  675.     is used. See documentation for Google ClientLogin here:
  676.     http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
  677.  
  678.     Args:
  679.       token: string or instance of a ClientLoginToken. 
  680.     """
  681.     if not isinstance(token, gdata.auth.ClientLoginToken):
  682.       token_string = token
  683.       token = gdata.auth.ClientLoginToken()
  684.       token.set_token_string(token_string)
  685.  
  686.     if not token.scopes:
  687.       if scopes is None:
  688.         scopes = lookup_scopes(self.service)
  689.         if scopes is None:
  690.           scopes = [atom.token_store.SCOPE_ALL]
  691.       token.scopes = scopes
  692.     if self.auto_set_current_token:
  693.       self.current_token = token
  694.     if self.auto_store_tokens:
  695.       self.token_store.add_token(token)
  696.  
  697.   # Private methods to create the source property.
  698.   def __GetSource(self):
  699.     return self.__source
  700.  
  701.   def __SetSource(self, new_source):
  702.     self.__source = new_source
  703.     # Update the UserAgent header to include the new application name.
  704.     self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
  705.         self.__source,)
  706.  
  707.   source = property(__GetSource, __SetSource, 
  708.       doc="""The source is the name of the application making the request. 
  709.              It should be in the form company_id-app_name-app_version""")
  710.  
  711.   # Authentication operations
  712.  
  713.   def ProgrammaticLogin(self, captcha_token=None, captcha_response=None):
  714.     """Authenticates the user and sets the GData Auth token.
  715.  
  716.     Login retreives a temporary auth token which must be used with all
  717.     requests to GData services. The auth token is stored in the GData client
  718.     object.
  719.  
  720.     Login is also used to respond to a captcha challenge. If the user's login
  721.     attempt failed with a CaptchaRequired error, the user can respond by
  722.     calling Login with the captcha token and the answer to the challenge.
  723.  
  724.     Args:
  725.       captcha_token: string (optional) The identifier for the captcha challenge
  726.                      which was presented to the user.
  727.       captcha_response: string (optional) The user's answer to the captch 
  728.                         challenge.
  729.  
  730.     Raises:
  731.       CaptchaRequired if the login service will require a captcha response
  732.       BadAuthentication if the login service rejected the username or password
  733.       Error if the login service responded with a 403 different from the above
  734.     """
  735.     request_body = gdata.auth.generate_client_login_request_body(self.email,
  736.         self.password, self.service, self.source, self.account_type,
  737.         captcha_token, captcha_response)
  738.  
  739.     # If the user has defined their own authentication service URL, 
  740.     # send the ClientLogin requests to this URL:
  741.     if not self.auth_service_url:
  742.         auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' 
  743.     else:
  744.         auth_request_url = self.auth_service_url
  745.  
  746.     auth_response = self.http_client.request('POST', auth_request_url,
  747.         data=request_body, 
  748.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  749.     response_body = auth_response.read()
  750.  
  751.     if auth_response.status == 200:
  752.       # TODO: insert the token into the token_store directly.
  753.       self.SetClientLoginToken(
  754.           gdata.auth.get_client_login_token(response_body))
  755.       self.__captcha_token = None
  756.       self.__captcha_url = None
  757.  
  758.     elif auth_response.status == 403:
  759.       # Examine each line to find the error type and the captcha token and
  760.       # captch URL if they are present.
  761.       captcha_parameters = gdata.auth.get_captcha_challenge(response_body,
  762.           captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
  763.       if captcha_parameters:
  764.         self.__captcha_token = captcha_parameters['token']
  765.         self.__captcha_url = captcha_parameters['url']
  766.         raise CaptchaRequired, 'Captcha Required'
  767.       elif response_body.splitlines()[0] == 'Error=BadAuthentication':
  768.         self.__captcha_token = None
  769.         self.__captcha_url = None
  770.         raise BadAuthentication, 'Incorrect username or password'
  771.       else:
  772.         self.__captcha_token = None
  773.         self.__captcha_url = None
  774.         raise Error, 'Server responded with a 403 code'
  775.     elif auth_response.status == 302:
  776.       self.__captcha_token = None
  777.       self.__captcha_url = None
  778.       # Google tries to redirect all bad URLs back to 
  779.       # http://www.google.<locale>. If a redirect
  780.       # attempt is made, assume the user has supplied an incorrect authentication URL
  781.       raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
  782.  
  783.   def ClientLogin(self, username, password, account_type=None, service=None,
  784.       auth_service_url=None, source=None, captcha_token=None, 
  785.       captcha_response=None):
  786.     """Convenience method for authenticating using ProgrammaticLogin. 
  787.     
  788.     Sets values for email, password, and other optional members.
  789.  
  790.     Args:
  791.       username:
  792.       password:
  793.       account_type: string (optional)
  794.       service: string (optional)
  795.       auth_service_url: string (optional)
  796.       captcha_token: string (optional)
  797.       captcha_response: string (optional)
  798.     """
  799.     self.email = username
  800.     self.password = password
  801.  
  802.     if account_type:
  803.       self.account_type = account_type
  804.     if service:
  805.       self.service = service
  806.     if source:
  807.       self.source = source
  808.     if auth_service_url:
  809.       self.auth_service_url = auth_service_url
  810.  
  811.     self.ProgrammaticLogin(captcha_token, captcha_response)
  812.  
  813.   def GenerateAuthSubURL(self, next, scope, secure=False, session=True, 
  814.       domain='default'):
  815.     """Generate a URL at which the user will login and be redirected back.
  816.  
  817.     Users enter their credentials on a Google login page and a token is sent
  818.     to the URL specified in next. See documentation for AuthSub login at:
  819.     http://code.google.com/apis/accounts/docs/AuthSub.html
  820.  
  821.     Args:
  822.       next: string The URL user will be sent to after logging in.
  823.       scope: string or list of strings. The URLs of the services to be 
  824.              accessed.
  825.       secure: boolean (optional) Determines whether or not the issued token
  826.               is a secure token.
  827.       session: boolean (optional) Determines whether or not the issued token
  828.                can be upgraded to a session token.
  829.     """
  830.     if not isinstance(scope, (list, tuple)):
  831.       scope = (scope,)
  832.     return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, 
  833.         session=session, 
  834.         request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, 
  835.         domain=domain)
  836.  
  837.   def UpgradeToSessionToken(self, token=None):
  838.     """Upgrades a single use AuthSub token to a session token.
  839.  
  840.     Args:
  841.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  842.              (optional) which is good for a single use but can be upgraded
  843.              to a session token. If no token is passed in, the token
  844.              is found by looking in the token_store by looking for a token
  845.              for the current scope.
  846.  
  847.     Raises:
  848.       NonAuthSubToken if the user's auth token is not an AuthSub token
  849.       TokenUpgradeFailed if the server responded to the request with an 
  850.       error.
  851.     """
  852.     if token is None:
  853.       scopes = lookup_scopes(self.service)
  854.       if scopes:
  855.         token = self.token_store.find_token(scopes[0])
  856.       else:
  857.         token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  858.     if not isinstance(token, gdata.auth.AuthSubToken):
  859.       raise NonAuthSubToken
  860.  
  861.     self.SetAuthSubToken(self.upgrade_to_session_token(token))
  862.  
  863.   def upgrade_to_session_token(self, token):
  864.     """Upgrades a single use AuthSub token to a session token.
  865.  
  866.     Args:
  867.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  868.              which is good for a single use but can be upgraded to a
  869.              session token.
  870.  
  871.     Returns:
  872.       The upgraded token as a gdata.auth.AuthSubToken object.
  873.  
  874.     Raises:
  875.       TokenUpgradeFailed if the server responded to the request with an 
  876.       error.
  877.     """
  878.     response = token.perform_request(self.http_client, 'GET', 
  879.         AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', 
  880.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  881.     response_body = response.read()
  882.     if response.status == 200:
  883.       token.set_token_string(
  884.           gdata.auth.token_from_http_body(response_body))
  885.       return token
  886.     else:
  887.       raise TokenUpgradeFailed({'status': response.status,
  888.                                 'reason': 'Non 200 response on upgrade',
  889.                                 'body': response_body})
  890.  
  891.   def RevokeAuthSubToken(self):
  892.     """Revokes an existing AuthSub token.
  893.  
  894.     Raises:
  895.       NonAuthSubToken if the user's auth token is not an AuthSub token
  896.     """
  897.     scopes = lookup_scopes(self.service)
  898.     token = self.token_store.find_token(scopes[0])
  899.     if not isinstance(token, gdata.auth.AuthSubToken):
  900.       raise NonAuthSubToken
  901.  
  902.     response = token.perform_request(self.http_client, 'GET', 
  903.         AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', 
  904.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  905.     if response.status == 200:
  906.       self.token_store.remove_token(token)
  907.  
  908.   def AuthSubTokenInfo(self):
  909.     """Fetches the AuthSub token's metadata from the server.
  910.  
  911.     Raises:
  912.       NonAuthSubToken if the user's auth token is not an AuthSub token
  913.     """
  914.     scopes = lookup_scopes(self.service)
  915.     token = self.token_store.find_token(scopes[0])
  916.     if not isinstance(token, gdata.auth.AuthSubToken):
  917.       raise NonAuthSubToken
  918.  
  919.     response = token.perform_request(self.http_client, 'GET', 
  920.         AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', 
  921.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  922.     result_body = response.read()
  923.     if response.status == 200:
  924.       return result_body
  925.     else:
  926.       raise RequestError, {'status': response.status,
  927.           'body': result_body}
  928.  
  929.   # CRUD operations
  930.   def Get(self, uri, extra_headers=None, redirects_remaining=4, 
  931.       encoding='UTF-8', converter=None):
  932.     """Query the GData API with the given URI
  933.  
  934.     The uri is the portion of the URI after the server value 
  935.     (ex: www.google.com).
  936.  
  937.     To perform a query against Google Base, set the server to 
  938.     'base.google.com' and set the uri to '/base/feeds/...', where ... is 
  939.     your query. For example, to find snippets for all digital cameras uri 
  940.     should be set to: '/base/feeds/snippets?bq=digital+camera'
  941.  
  942.     Args:
  943.       uri: string The query in the form of a URI. Example:
  944.            '/base/feeds/snippets?bq=digital+camera'.
  945.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  946.                      in the GET request. These headers are in addition to 
  947.                      those stored in the client's additional_headers property.
  948.                      The client automatically sets the Content-Type and 
  949.                      Authorization headers.
  950.       redirects_remaining: int (optional) Tracks the number of additional
  951.           redirects this method will allow. If the service object receives
  952.           a redirect and remaining is 0, it will not follow the redirect. 
  953.           This was added to avoid infinite redirect loops.
  954.       encoding: string (optional) The character encoding for the server's
  955.           response. Default is UTF-8
  956.       converter: func (optional) A function which will transform
  957.           the server's results before it is returned. Example: use 
  958.           GDataFeedFromString to parse the server response as if it
  959.           were a GDataFeed.
  960.  
  961.     Returns:
  962.       If there is no ResultsTransformer specified in the call, a GDataFeed 
  963.       or GDataEntry depending on which is sent from the server. If the 
  964.       response is niether a feed or entry and there is no ResultsTransformer,
  965.       return a string. If there is a ResultsTransformer, the returned value 
  966.       will be that of the ResultsTransformer function.
  967.     """
  968.  
  969.     if extra_headers is None:
  970.       extra_headers = {}
  971.  
  972.     if self.__gsessionid is not None:
  973.       if uri.find('gsessionid=') < 0:
  974.         if uri.find('?') > -1:
  975.           uri += '&gsessionid=%s' % (self.__gsessionid,)
  976.         else:
  977.           uri += '?gsessionid=%s' % (self.__gsessionid,)
  978.  
  979.     server_response = self.request('GET', uri, 
  980.         headers=extra_headers)
  981.     result_body = server_response.read()
  982.  
  983.     if server_response.status == 200:
  984.       if converter:
  985.         return converter(result_body)
  986.       # There was no ResultsTransformer specified, so try to convert the
  987.       # server's response into a GDataFeed.
  988.       feed = gdata.GDataFeedFromString(result_body)
  989.       if not feed:
  990.         # If conversion to a GDataFeed failed, try to convert the server's
  991.         # response to a GDataEntry.
  992.         entry = gdata.GDataEntryFromString(result_body)
  993.         if not entry:
  994.           # The server's response wasn't a feed, or an entry, so return the
  995.           # response body as a string.
  996.           return result_body
  997.         return entry
  998.       return feed
  999.     elif server_response.status == 302:
  1000.       if redirects_remaining > 0:
  1001.         location = server_response.getheader('Location')
  1002.         if location is not None:
  1003.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1004.           if m is not None:
  1005.             self.__gsessionid = m.group(1)
  1006.           return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, 
  1007.               encoding=encoding, converter=converter)
  1008.         else:
  1009.           raise RequestError, {'status': server_response.status,
  1010.               'reason': '302 received without Location header',
  1011.               'body': result_body}
  1012.       else:
  1013.         raise RequestError, {'status': server_response.status,
  1014.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1015.             'body': result_body}
  1016.     else:
  1017.       raise RequestError, {'status': server_response.status,
  1018.           'reason': server_response.reason, 'body': result_body}
  1019.  
  1020.   def GetMedia(self, uri, extra_headers=None):
  1021.     """Returns a MediaSource containing media and its metadata from the given
  1022.     URI string.
  1023.     """
  1024.     response_handle = self.request('GET', uri,
  1025.         headers=extra_headers)
  1026.     return gdata.MediaSource(response_handle, response_handle.getheader(
  1027.             'Content-Type'),
  1028.         response_handle.getheader('Content-Length'))
  1029.  
  1030.   def GetEntry(self, uri, extra_headers=None):
  1031.     """Query the GData API with the given URI and receive an Entry.
  1032.     
  1033.     See also documentation for gdata.service.Get
  1034.  
  1035.     Args:
  1036.       uri: string The query in the form of a URI. Example:
  1037.            '/base/feeds/snippets?bq=digital+camera'.
  1038.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1039.                      in the GET request. These headers are in addition to
  1040.                      those stored in the client's additional_headers property.
  1041.                      The client automatically sets the Content-Type and
  1042.                      Authorization headers.
  1043.  
  1044.     Returns:
  1045.       A GDataEntry built from the XML in the server's response.
  1046.     """
  1047.  
  1048.     result = GDataService.Get(self, uri, extra_headers, 
  1049.         converter=atom.EntryFromString)
  1050.     if isinstance(result, atom.Entry):
  1051.       return result
  1052.     else:
  1053.       raise UnexpectedReturnType, 'Server did not send an entry' 
  1054.  
  1055.   def GetFeed(self, uri, extra_headers=None, 
  1056.               converter=gdata.GDataFeedFromString):
  1057.     """Query the GData API with the given URI and receive a Feed.
  1058.  
  1059.     See also documentation for gdata.service.Get
  1060.  
  1061.     Args:
  1062.       uri: string The query in the form of a URI. Example:
  1063.            '/base/feeds/snippets?bq=digital+camera'.
  1064.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1065.                      in the GET request. These headers are in addition to
  1066.                      those stored in the client's additional_headers property.
  1067.                      The client automatically sets the Content-Type and
  1068.                      Authorization headers.
  1069.  
  1070.     Returns:
  1071.       A GDataFeed built from the XML in the server's response.
  1072.     """
  1073.  
  1074.     result = GDataService.Get(self, uri, extra_headers, converter=converter)
  1075.     if isinstance(result, atom.Feed):
  1076.       return result
  1077.     else:
  1078.       raise UnexpectedReturnType, 'Server did not send a feed'  
  1079.  
  1080.   def GetNext(self, feed):
  1081.     """Requests the next 'page' of results in the feed.
  1082.     
  1083.     This method uses the feed's next link to request an additional feed
  1084.     and uses the class of the feed to convert the results of the GET request.
  1085.  
  1086.     Args:
  1087.       feed: atom.Feed or a subclass. The feed should contain a next link and
  1088.           the type of the feed will be applied to the results from the 
  1089.           server. The new feed which is returned will be of the same class
  1090.           as this feed which was passed in.
  1091.  
  1092.     Returns:
  1093.       A new feed representing the next set of results in the server's feed.
  1094.       The type of this feed will match that of the feed argument.
  1095.     """
  1096.     next_link = feed.GetNextLink()
  1097.     # Create a closure which will convert an XML string to the class of
  1098.     # the feed object passed in.
  1099.     def ConvertToFeedClass(xml_string):
  1100.       return atom.CreateClassFromXMLString(feed.__class__, xml_string)
  1101.     # Make a GET request on the next link and use the above closure for the
  1102.     # converted which processes the XML string from the server.
  1103.     if next_link and next_link.href:
  1104.       return GDataService.Get(self, next_link.href, 
  1105.           converter=ConvertToFeedClass)
  1106.     else:
  1107.       return None
  1108.  
  1109.   def Post(self, data, uri, extra_headers=None, url_params=None,
  1110.            escape_params=True, redirects_remaining=4, media_source=None,
  1111.            converter=None):
  1112.     """Insert or update  data into a GData service at the given URI.
  1113.  
  1114.     Args:
  1115.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1116.             XML to be sent to the uri.
  1117.       uri: string The location (feed) to which the data should be inserted.
  1118.            Example: '/base/feeds/items'.
  1119.       extra_headers: dict (optional) HTTP headers which are to be included.
  1120.                      The client automatically sets the Content-Type,
  1121.                      Authorization, and Content-Length headers.
  1122.       url_params: dict (optional) Additional URL parameters to be included
  1123.                   in the URI. These are translated into query arguments
  1124.                   in the form '&dict_key=value&...'.
  1125.                   Example: {'max-results': '250'} becomes &max-results=250
  1126.       escape_params: boolean (optional) If false, the calling code has already
  1127.                      ensured that the query will form a valid URL (all
  1128.                      reserved characters have been escaped). If true, this
  1129.                      method will escape the query and any URL parameters
  1130.                      provided.
  1131.       media_source: MediaSource (optional) Container for the media to be sent
  1132.           along with the entry, if provided.
  1133.       converter: func (optional) A function which will be executed on the
  1134.           server's response. Often this is a function like
  1135.           GDataEntryFromString which will parse the body of the server's
  1136.           response and return a GDataEntry.
  1137.  
  1138.     Returns:
  1139.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1140.       or the results of running converter on the server's result body (if
  1141.       converter was specified).
  1142.     """
  1143.     return GDataService.PostOrPut(self, 'POST', data, uri, 
  1144.         extra_headers=extra_headers, url_params=url_params, 
  1145.         escape_params=escape_params, redirects_remaining=redirects_remaining,
  1146.         media_source=media_source, converter=converter)
  1147.  
  1148.   def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, 
  1149.            escape_params=True, redirects_remaining=4, media_source=None, 
  1150.            converter=None):
  1151.     """Insert data into a GData service at the given URI.
  1152.  
  1153.     Args:
  1154.       verb: string, either 'POST' or 'PUT'
  1155.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1156.             XML to be sent to the uri. 
  1157.       uri: string The location (feed) to which the data should be inserted. 
  1158.            Example: '/base/feeds/items'. 
  1159.       extra_headers: dict (optional) HTTP headers which are to be included. 
  1160.                      The client automatically sets the Content-Type,
  1161.                      Authorization, and Content-Length headers.
  1162.       url_params: dict (optional) Additional URL parameters to be included
  1163.                   in the URI. These are translated into query arguments
  1164.                   in the form '&dict_key=value&...'.
  1165.                   Example: {'max-results': '250'} becomes &max-results=250
  1166.       escape_params: boolean (optional) If false, the calling code has already
  1167.                      ensured that the query will form a valid URL (all
  1168.                      reserved characters have been escaped). If true, this
  1169.                      method will escape the query and any URL parameters
  1170.                      provided.
  1171.       media_source: MediaSource (optional) Container for the media to be sent
  1172.           along with the entry, if provided.
  1173.       converter: func (optional) A function which will be executed on the 
  1174.           server's response. Often this is a function like 
  1175.           GDataEntryFromString which will parse the body of the server's 
  1176.           response and return a GDataEntry.
  1177.  
  1178.     Returns:
  1179.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1180.       or the results of running converter on the server's result body (if
  1181.       converter was specified).
  1182.     """
  1183.     if extra_headers is None:
  1184.       extra_headers = {}
  1185.  
  1186.     if self.__gsessionid is not None:
  1187.       if uri.find('gsessionid=') < 0:
  1188.         if uri.find('?') > -1:
  1189.           uri += '&gsessionid=%s' % (self.__gsessionid,)
  1190.         else:
  1191.           uri += '?gsessionid=%s' % (self.__gsessionid,)
  1192.  
  1193.     if data and media_source:
  1194.       if ElementTree.iselement(data):
  1195.         data_str = ElementTree.tostring(data)
  1196.       else:
  1197.         data_str = str(data)
  1198.         
  1199.       multipart = []
  1200.       multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
  1201.           'Content-Type: application/atom+xml\r\n\r\n')
  1202.       multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
  1203.           media_source.content_type+'\r\n\r\n')
  1204.       multipart.append('\r\n--END_OF_PART--\r\n')
  1205.         
  1206.       extra_headers['MIME-version'] = '1.0'
  1207.       extra_headers['Content-Length'] = str(len(multipart[0]) +
  1208.           len(multipart[1]) + len(multipart[2]) +
  1209.           len(data_str) + media_source.content_length)
  1210.  
  1211.       extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART'
  1212.       server_response = self.request(verb, uri, 
  1213.           data=[multipart[0], data_str, multipart[1], media_source.file_handle,
  1214.               multipart[2]], headers=extra_headers)
  1215.       result_body = server_response.read()
  1216.       
  1217.     elif media_source or isinstance(data, gdata.MediaSource):
  1218.       if isinstance(data, gdata.MediaSource):
  1219.         media_source = data
  1220.       extra_headers['Content-Length'] = str(media_source.content_length)
  1221.       extra_headers['Content-Type'] = media_source.content_type
  1222.       server_response = self.request(verb, uri, 
  1223.           data=media_source.file_handle, headers=extra_headers)
  1224.       result_body = server_response.read()
  1225.  
  1226.     else:
  1227.       http_data = data
  1228.       content_type = 'application/atom+xml'
  1229.       extra_headers['Content-Type'] = content_type
  1230.       server_response = self.request(verb, uri, data=http_data,
  1231.           headers=extra_headers)
  1232.       result_body = server_response.read()
  1233.  
  1234.     # Server returns 201 for most post requests, but when performing a batch
  1235.     # request the server responds with a 200 on success.
  1236.     if server_response.status == 201 or server_response.status == 200:
  1237.       if converter:
  1238.         return converter(result_body)
  1239.       feed = gdata.GDataFeedFromString(result_body)
  1240.       if not feed:
  1241.         entry = gdata.GDataEntryFromString(result_body)
  1242.         if not entry:
  1243.           return result_body
  1244.         return entry
  1245.       return feed
  1246.     elif server_response.status == 302:
  1247.       if redirects_remaining > 0:
  1248.         location = server_response.getheader('Location')
  1249.         if location is not None:
  1250.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1251.           if m is not None:
  1252.             self.__gsessionid = m.group(1) 
  1253.           return GDataService.PostOrPut(self, verb, data, location, 
  1254.               extra_headers, url_params, escape_params, 
  1255.               redirects_remaining - 1, media_source, converter=converter)
  1256.         else:
  1257.           raise RequestError, {'status': server_response.status,
  1258.               'reason': '302 received without Location header',
  1259.               'body': result_body}
  1260.       else:
  1261.         raise RequestError, {'status': server_response.status,
  1262.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1263.             'body': result_body}
  1264.     else:
  1265.       raise RequestError, {'status': server_response.status,
  1266.           'reason': server_response.reason, 'body': result_body}
  1267.  
  1268.   def Put(self, data, uri, extra_headers=None, url_params=None, 
  1269.           escape_params=True, redirects_remaining=3, media_source=None,
  1270.           converter=None):
  1271.     """Updates an entry at the given URI.
  1272.      
  1273.     Args:
  1274.       data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
  1275.             XML containing the updated data.
  1276.       uri: string A URI indicating entry to which the update will be applied.
  1277.            Example: '/base/feeds/items/ITEM-ID'
  1278.       extra_headers: dict (optional) HTTP headers which are to be included.
  1279.                      The client automatically sets the Content-Type,
  1280.                      Authorization, and Content-Length headers.
  1281.       url_params: dict (optional) Additional URL parameters to be included
  1282.                   in the URI. These are translated into query arguments
  1283.                   in the form '&dict_key=value&...'.
  1284.                   Example: {'max-results': '250'} becomes &max-results=250
  1285.       escape_params: boolean (optional) If false, the calling code has already
  1286.                      ensured that the query will form a valid URL (all
  1287.                      reserved characters have been escaped). If true, this
  1288.                      method will escape the query and any URL parameters
  1289.                      provided.
  1290.       converter: func (optional) A function which will be executed on the 
  1291.           server's response. Often this is a function like 
  1292.           GDataEntryFromString which will parse the body of the server's 
  1293.           response and return a GDataEntry.
  1294.  
  1295.     Returns:
  1296.       If the put succeeded, this method will return a GDataFeed, GDataEntry,
  1297.       or the results of running converter on the server's result body (if
  1298.       converter was specified).
  1299.     """
  1300.     return GDataService.PostOrPut(self, 'PUT', data, uri, 
  1301.         extra_headers=extra_headers, url_params=url_params, 
  1302.         escape_params=escape_params, redirects_remaining=redirects_remaining,
  1303.         media_source=media_source, converter=converter)
  1304.  
  1305.   def Delete(self, uri, extra_headers=None, url_params=None, 
  1306.              escape_params=True, redirects_remaining=4):
  1307.     """Deletes the entry at the given URI.
  1308.  
  1309.     Args:
  1310.       uri: string The URI of the entry to be deleted. Example: 
  1311.            '/base/feeds/items/ITEM-ID'
  1312.       extra_headers: dict (optional) HTTP headers which are to be included.
  1313.                      The client automatically sets the Content-Type and
  1314.                      Authorization headers.
  1315.       url_params: dict (optional) Additional URL parameters to be included
  1316.                   in the URI. These are translated into query arguments
  1317.                   in the form '&dict_key=value&...'.
  1318.                   Example: {'max-results': '250'} becomes &max-results=250
  1319.       escape_params: boolean (optional) If false, the calling code has already
  1320.                      ensured that the query will form a valid URL (all
  1321.                      reserved characters have been escaped). If true, this
  1322.                      method will escape the query and any URL parameters
  1323.                      provided.
  1324.  
  1325.     Returns:
  1326.       True if the entry was deleted.
  1327.     """
  1328.     if extra_headers is None:
  1329.       extra_headers = {}
  1330.  
  1331.     if self.__gsessionid is not None:
  1332.       if uri.find('gsessionid=') < 0:
  1333.         if uri.find('?') > -1:
  1334.           uri += '&gsessionid=%s' % (self.__gsessionid,)
  1335.         else:
  1336.           uri += '?gsessionid=%s' % (self.__gsessionid,)
  1337.  
  1338.     server_response = self.request('DELETE', uri, 
  1339.         headers=extra_headers)
  1340.     result_body = server_response.read()
  1341.  
  1342.     if server_response.status == 200:
  1343.       return True
  1344.     elif server_response.status == 302:
  1345.       if redirects_remaining > 0:
  1346.         location = server_response.getheader('Location')
  1347.         if location is not None:
  1348.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1349.           if m is not None:
  1350.             self.__gsessionid = m.group(1) 
  1351.           return GDataService.Delete(self, location, extra_headers, 
  1352.               url_params, escape_params, redirects_remaining - 1)
  1353.         else:
  1354.           raise RequestError, {'status': server_response.status,
  1355.               'reason': '302 received without Location header',
  1356.               'body': result_body}
  1357.       else:
  1358.         raise RequestError, {'status': server_response.status,
  1359.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1360.             'body': result_body}
  1361.     else:
  1362.       raise RequestError, {'status': server_response.status,
  1363.           'reason': server_response.reason, 'body': result_body}
  1364.  
  1365.  
  1366. def ExtractToken(url, scopes_included_in_next=True):
  1367.   """Gets the AuthSub token from the current page's URL.
  1368.  
  1369.   Designed to be used on the URL that the browser is sent to after the user
  1370.   authorizes this application at the page given by GenerateAuthSubRequestUrl.
  1371.  
  1372.   Args:
  1373.     url: The current page's URL. It should contain the token as a URL
  1374.         parameter. Example: 'http://example.com/?...&token=abcd435'
  1375.     scopes_included_in_next: If True, this function looks for a scope value
  1376.         associated with the token. The scope is a URL parameter with the
  1377.         key set to SCOPE_URL_PARAM_NAME. This parameter should be present
  1378.         if the AuthSub request URL was generated using
  1379.         GenerateAuthSubRequestUrl with include_scope_in_next set to True.
  1380.  
  1381.   Returns:
  1382.     A tuple containing the token string and a list of scope strings for which
  1383.     this token should be valid. If the scope was not included in the URL, the
  1384.     tuple will contain (token, None).
  1385.   """
  1386.   parsed = urlparse.urlparse(url)
  1387.   token = gdata.auth.AuthSubTokenFromUrl(parsed[4])
  1388.   scopes = ''
  1389.   if scopes_included_in_next:
  1390.     for pair in parsed[4].split('&'):
  1391.       if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME):
  1392.         scopes = urllib.unquote_plus(pair.split('=')[1])
  1393.   return (token, scopes.split(' '))
  1394.  
  1395.  
  1396. def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False,
  1397.     session=True, request_url='http://www.google.com/accounts/AuthSubRequest',
  1398.     include_scopes_in_next=True):
  1399.   """Creates a URL to request an AuthSub token to access Google services.
  1400.  
  1401.   For more details on AuthSub, see the documentation here:
  1402.   http://code.google.com/apis/accounts/docs/AuthSub.html
  1403.  
  1404.   Args:
  1405.     next: The URL where the browser should be sent after the user authorizes
  1406.         the application. This page is responsible for receiving the token
  1407.         which is embeded in the URL as a parameter.
  1408.     scopes: The base URL to which access will be granted. Example:
  1409.         'http://www.google.com/calendar/feeds' will grant access to all
  1410.         URLs in the Google Calendar data API. If you would like a token for
  1411.         multiple scopes, pass in a list of URL strings.
  1412.     hd: The domain to which the user's account belongs. This is set to the
  1413.         domain name if you are using Google Apps. Example: 'example.org'
  1414.         Defaults to 'default'
  1415.     secure: If set to True, all requests should be signed. The default is
  1416.         False.
  1417.     session: If set to True, the token received by the 'next' URL can be
  1418.         upgraded to a multiuse session token. If session is set to False, the
  1419.         token may only be used once and cannot be upgraded. Default is True.
  1420.     request_url: The base of the URL to which the user will be sent to
  1421.         authorize this application to access their data. The default is
  1422.         'http://www.google.com/accounts/AuthSubRequest'.
  1423.     include_scopes_in_next: Boolean if set to true, the 'next' parameter will
  1424.         be modified to include the requested scope as a URL parameter. The
  1425.         key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The
  1426.         benefit of including the scope URL as a parameter to the next URL, is
  1427.         that the page which receives the AuthSub token will be able to tell
  1428.         which URLs the token grants access to.
  1429.  
  1430.   Returns:
  1431.     A URL string to which the browser should be sent.
  1432.   """
  1433.   if isinstance(scopes, list):
  1434.     scope = ' '.join(scopes)
  1435.   else:
  1436.     scope = scopes
  1437.   if include_scopes_in_next:
  1438.     if next.find('?') > -1:
  1439.       next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope})
  1440.     else:
  1441.       next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope})
  1442.   return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure,
  1443.       session=session, request_url=request_url, domain=hd)
  1444.  
  1445.  
  1446. class Query(dict):
  1447.   """Constructs a query URL to be used in GET requests
  1448.   
  1449.   Url parameters are created by adding key-value pairs to this object as a 
  1450.   dict. For example, to add &max-results=25 to the URL do
  1451.   my_query['max-results'] = 25
  1452.  
  1453.   Category queries are created by adding category strings to the categories
  1454.   member. All items in the categories list will be concatenated with the /
  1455.   symbol (symbolizing a category x AND y restriction). If you would like to OR
  1456.   2 categories, append them as one string with a | between the categories. 
  1457.   For example, do query.categories.append('Fritz|Laurie') to create a query
  1458.   like this feed/-/Fritz%7CLaurie . This query will look for results in both
  1459.   categories.
  1460.   """
  1461.  
  1462.   def __init__(self, feed=None, text_query=None, params=None, 
  1463.       categories=None):
  1464.     """Constructor for Query
  1465.     
  1466.     Args:
  1467.       feed: str (optional) The path for the feed (Examples: 
  1468.           '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
  1469.       text_query: str (optional) The contents of the q query parameter. The
  1470.           contents of the text_query are URL escaped upon conversion to a URI.
  1471.       params: dict (optional) Parameter value string pairs which become URL
  1472.           params when translated to a URI. These parameters are added to the
  1473.           query's items (key-value pairs).
  1474.       categories: list (optional) List of category strings which should be
  1475.           included as query categories. See 
  1476.           http://code.google.com/apis/gdata/reference.html#Queries for 
  1477.           details. If you want to get results from category A or B (both 
  1478.           categories), specify a single list item 'A|B'. 
  1479.     """
  1480.     
  1481.     self.feed = feed
  1482.     self.categories = []
  1483.     if text_query:
  1484.       self.text_query = text_query
  1485.     if isinstance(params, dict):
  1486.       for param in params:
  1487.         self[param] = params[param]
  1488.     if isinstance(categories, list):
  1489.       for category in categories:
  1490.         self.categories.append(category)
  1491.  
  1492.   def _GetTextQuery(self):
  1493.     if 'q' in self.keys():
  1494.       return self['q']
  1495.     else:
  1496.       return None
  1497.  
  1498.   def _SetTextQuery(self, query):
  1499.     self['q'] = query
  1500.  
  1501.   text_query = property(_GetTextQuery, _SetTextQuery, 
  1502.       doc="""The feed query's q parameter""")
  1503.  
  1504.   def _GetAuthor(self):
  1505.     if 'author' in self.keys():
  1506.       return self['author']
  1507.     else:
  1508.       return None
  1509.  
  1510.   def _SetAuthor(self, query):
  1511.     self['author'] = query
  1512.  
  1513.   author = property(_GetAuthor, _SetAuthor,
  1514.       doc="""The feed query's author parameter""")
  1515.  
  1516.   def _GetAlt(self):
  1517.     if 'alt' in self.keys():
  1518.       return self['alt']
  1519.     else:
  1520.       return None
  1521.  
  1522.   def _SetAlt(self, query):
  1523.     self['alt'] = query
  1524.  
  1525.   alt = property(_GetAlt, _SetAlt,
  1526.       doc="""The feed query's alt parameter""")
  1527.  
  1528.   def _GetUpdatedMin(self):
  1529.     if 'updated-min' in self.keys():
  1530.       return self['updated-min']
  1531.     else:
  1532.       return None
  1533.  
  1534.   def _SetUpdatedMin(self, query):
  1535.     self['updated-min'] = query
  1536.  
  1537.   updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
  1538.       doc="""The feed query's updated-min parameter""")
  1539.  
  1540.   def _GetUpdatedMax(self):
  1541.     if 'updated-max' in self.keys():
  1542.       return self['updated-max']
  1543.     else:
  1544.       return None
  1545.  
  1546.   def _SetUpdatedMax(self, query):
  1547.     self['updated-max'] = query
  1548.  
  1549.   updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
  1550.       doc="""The feed query's updated-max parameter""")
  1551.  
  1552.   def _GetPublishedMin(self):
  1553.     if 'published-min' in self.keys():
  1554.       return self['published-min']
  1555.     else:
  1556.       return None
  1557.  
  1558.   def _SetPublishedMin(self, query):
  1559.     self['published-min'] = query
  1560.  
  1561.   published_min = property(_GetPublishedMin, _SetPublishedMin,
  1562.       doc="""The feed query's published-min parameter""")
  1563.  
  1564.   def _GetPublishedMax(self):
  1565.     if 'published-max' in self.keys():
  1566.       return self['published-max']
  1567.     else:
  1568.       return None
  1569.  
  1570.   def _SetPublishedMax(self, query):
  1571.     self['published-max'] = query
  1572.  
  1573.   published_max = property(_GetPublishedMax, _SetPublishedMax,
  1574.       doc="""The feed query's published-max parameter""")
  1575.  
  1576.   def _GetStartIndex(self):
  1577.     if 'start-index' in self.keys():
  1578.       return self['start-index']
  1579.     else:
  1580.       return None
  1581.  
  1582.   def _SetStartIndex(self, query):
  1583.     if not isinstance(query, str):
  1584.       query = str(query)
  1585.     self['start-index'] = query
  1586.  
  1587.   start_index = property(_GetStartIndex, _SetStartIndex,
  1588.       doc="""The feed query's start-index parameter""")
  1589.  
  1590.   def _GetMaxResults(self):
  1591.     if 'max-results' in self.keys():
  1592.       return self['max-results']
  1593.     else:
  1594.       return None
  1595.  
  1596.   def _SetMaxResults(self, query):
  1597.     if not isinstance(query, str):
  1598.       query = str(query)
  1599.     self['max-results'] = query
  1600.  
  1601.   max_results = property(_GetMaxResults, _SetMaxResults,
  1602.       doc="""The feed query's max-results parameter""")
  1603.  
  1604.   def _GetOrderBy(self):
  1605.     if 'orderby' in self.keys():
  1606.       return self['orderby']
  1607.     else:
  1608.       return None
  1609.  
  1610.   def _SetOrderBy(self, query):
  1611.     self['orderby'] = query
  1612.   
  1613.   orderby = property(_GetOrderBy, _SetOrderBy, 
  1614.       doc="""The feed query's orderby parameter""")
  1615.  
  1616.   def ToUri(self):
  1617.     q_feed = self.feed or ''
  1618.     category_string = '/'.join(
  1619.         [urllib.quote_plus(c) for c in self.categories])
  1620.     # Add categories to the feed if there are any.
  1621.     if len(self.categories) > 0:
  1622.       q_feed = q_feed + '/-/' + category_string
  1623.     return atom.service.BuildUri(q_feed, self)
  1624.  
  1625.   def __str__(self):
  1626.     return self.ToUri()
  1627.